#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int list_append(NODE_T **head, int num)
{
    NODE_T *tmp = NULL;
    NODE_T *new_node = NULL;

    // 容错判断
    if (head == NULL)
    {
        perror("head = null?");
        goto err0;
    }
    tmp = *head;

    // 创建节点
    new_node = malloc(sizeof(NODE_T));
    if (new_node == NULL)
    {
        perror("malloc");
        goto err0;
    }
    memset(new_node, 0, sizeof(NODE_T));

    // 数据写入
    new_node->num = num;

    // 无头单向链表写入
    if (tmp == NULL)
    {
        *head = new_node;
    }
    else 
    {
        while (tmp->next != NULL)
        {
            tmp = tmp->next;
        }
        tmp->next = new_node;
    }

    return 0;

err0:
    return -1;
}

int list_tarverse(NODE_T *head)
{
    // 容错判断
    if (head == NULL)
    {
        printf("无数据\n");
        return 0;
    }

    while (head != NULL)
    {
        printf("%d\n", head->num);
        head = head->next;
    }



    return 0;
}

int head_insert(NODE_T **head, int num)
{
    NODE_T *new_node = NULL;

    // 容错判断
    if (head == NULL)
    {
        perror("&head=null...");
        goto err0;
    }

    // 创建节点空间
    new_node = malloc(sizeof(NODE_T));
    if (new_node == NULL)
    {
        perror("malloc fail...");
        goto err0;
    }
    memset(new_node, 0, sizeof(NODE_T));

    // 数据写入
    new_node->num = num;

    // 头部插入链表
    new_node->next = (*head);
    *head = new_node;

    return 0;

err0:
    return -1;
}

int list_destroy(NODE_T **head)
{
    NODE_T *tmp = NULL;
    NODE_T *save = NULL;

    // 容错判断
    if (head == NULL)
    {
        perror("&head=null?");
        goto err0;
    }

    tmp = *head;

    while (tmp != NULL)
    {
        save = tmp->next;
        free(tmp);
        tmp = save;
    }

    return 0;

err0:
    return -1;
}